/*
 * @Author: sean_kei@163.com
 * @Date: 2021-06-08 15:07:55
 * @LastEditors: sean_kei@163.com
 * @LastEditTime: 2022-08-04 14:17:45
 */
package com.wxhandle.cleandemo.sso.service;

import java.util.ArrayList;
import java.util.List;

import com.wxhandle.cleandemo.core.domain.identity.SysRole;
import com.wxhandle.cleandemo.core.domain.identity.SysUser;
import com.wxhandle.cleandemo.core.services.SysUserService;
import com.wxhandle.cleandemo.sso.entity.CarbonUser;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserService userService;
    /**
	 * The constructor is annotated with @Autowired, meaning that it injects the UserPrincipalRepository<UserPrincipal>
	 * implementation. This annotation can be omitted; Spring automatically injects any declared dependency since version 4.3.
	 */
	public UserDetailsServiceImpl(SysUserService userPrincipalRepository) {
		this.userService = userPrincipalRepository;
	}

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.getOneByLogin(username);
        if(user == null)
            throw new UsernameNotFoundException("用户或密码错误");
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (SysRole role : user.getRoles()) {
            authorities.add(new SimpleGrantedAuthority(role.getId()));
        }
        return CarbonUser.of(user); // new User(user.getName(), user.getPwd(), authorities);
    }

}
